import storage from "./storage";
import constant from '@/utils/constant';
import store from '@/store';
import config from '@/config'

/**
 * 浏览器记录 KEY
 */
const getKey = () => {
	const {
		user
	} = store.state;
	return `${constant.history}-${user.phone}-${user.type}`
}

/**
 * 添加浏览记录
 */
export const setHistory = (data) => {
	const key = getKey();
	const json = uni.getStorageSync(key)
	if (json) {
		const historyList = JSON.parse(json);
		const isExist = historyList.findIndex(n => data.id === n.id);
		if (isExist >= 0) {
			return;
		}
		if (config.historyMax <= historyList.length) {
			// 删除最后一个元素
			historyList.pop();
		}
		historyList.unshift(data)
		uni.setStorageSync(key, JSON.stringify(historyList));
	} else {
		uni.setStorageSync(key, JSON.stringify([data]));
	}
}

/**
 * 获取浏览记录
 */
export const getHistory = () => {
	const key = getKey();
	const json = uni.getStorageSync(key)
	if (json) {
		return JSON.parse(json);
	}
	return [];
}

/**
 * 清空浏览记录
 */
export const removeHistory = () => {
	const key = getKey();
	uni.removeStorageSync(key);
}